<?php
/**
 * Created by PhpStorm.
 * User: czw
 * Date: 2018/7/11
 * Time: 14:59
 */
namespace app\common\model;


use app\lib\exception\BaseException;

class DrawTime extends BaseModel
{
    public function createOne($data)
    {
        return self::create($data);
    }

    private static function createOneByUserId($user_id)
    {
        $data = [
            'user_id' => $user_id,
            'remain_times' => config('common.daily_times'),
            'date'=>date('Y-n-j')
        ];
        $res = self::create($data);
        if (!$res) throw new BaseException(['msg' => '创建记录失败！']);
        return $res;
    }

    public static function getByUserId($user_id)
    {
        $res = self::where(['user_id' => $user_id])->find();
        if (!$res) {
            $res = self::createOneByUserId($user_id);
        }
        return $res;
    }

    public static function updateLastTime($user_id, $time)
    {
        $res = self::getByUserId($user_id);
        $time = time();
        $data = [
            'last_draw_time' => $time,
            'date' => date('Y-n-j', $time),
            'remain_times' => ($res->remain_times - 1) > 0 ? ($res->remain_times - 1) : 0,
        ];
        $result = self::where(['user_id' => $user_id])->update($data);
        if (!$result) throw new BaseException(['msg' => '时间更新失败！']);
    }
}